/**
 * Created by Fulwin on 2017/2/16.
 */

$(document).ready(function () {

    // 初始化layui组件
    layui.use(['layer', 'form'], function () {
        var layer = layui.layer,
            form = layui.form();

        var SUB_NAME;
        var SUB_ID;
        var PAGE;

        var attachmentData = new Array();	//定义存放附件的对象

        // 定义webuploader配置
        var webuploader_option = {
            auto: false,
            server: ThinkPHP['AJAX'] + '/Project/upload',
            pick: '#filePicker',
            fileVal: 'Filedata',
            accept: {
                title: 'file',
                extensions: 'zip,rar,jpg,png,jpeg,doc,xls,gif,xlsx,docx,pdf',
            },
            method: 'POST',
        };

        // 实例化webuploader
        var uploader = WebUploader.create(webuploader_option);

        // 添加到队列时
        uploader.on('fileQueued', function (file) {
            var fileItem = '<div class="file-item" id="' + file.id + '">' +
                '<div class="pull-left"><i class="file-icon file-icon-ext-' + file.ext + '"></i> ' + file.name + '</div>' +
                '<div class="pull-right"><i class="icon-remove" title="移除该文件"></i></div>' +
                '<div class="clearfix"></div>' +
                '</div>';
            $(webuploader_option.pick).next().append(fileItem);
        });

        // 上传之前
        uploader.on('uploadBeforeSend', function (block, data, headers) {

            data.SUB_NAME = SUB_NAME;
            data.DIR = '/Porject/';

        });

        //上传成功时
        uploader.on('uploadSuccess', function (file, response) {	//文件了上传成功后触发

            if (response.flag > 0) {
                //当文件上传成功后添加到attachmentData
                var attachmentObject = new Object();
                attachmentObject.savename = response.savename;
                attachmentObject.ext = response.ext;
                attachmentObject.path = response.path;
                attachmentData.push(attachmentObject);
            } else {
                layer.closeAll();
                layer.msg(response.msg, {icon: 2, time: 2000});
            }
        });

        // 所有文件上传结束时
        uploader.on('uploadFinished', function () {

            $.ajax({
                url: ThinkPHP['AJAX'] + '/Project/insertAttachment',
                type: 'POST',
                data: {
                    SUB_ID: SUB_ID,
                    attachments: JSON.stringify(attachmentData)
                },
                dataType: 'json',
                success: function (response) {
                    if (response.flag > 0) {
                        layer.closeAll();
                        layer.msg(response.msg, {icon: 1, time: 2000});
                        setTimeout(function () {
                            location.href = 'http://' + ThinkPHP['HTTP_HOST'] + '/Project/details/tab/discuss/id/' + SUB_NAME + '/p/' + PAGE;
                            //location.reload();
                        }, 2000);
                    } else {
                        layer.closeAll();
                        layer.msg(response.msg, {icon: 2, time: 2000});
                    }
                }
            });
        });

        // 上传错误时
        uploader.on('error', function (code) {
            var msg = '';
            switch (code) {
                case 'Q_EXCEED_NUM_LIMIT':
                    msg = '只能上传一个文件';
                    break;
                case 'Q_EXCEED_SIZE_LIMIT':
                    msg = '文件大小超出限制';
                    break;
                case 'Q_TYPE_DENIED':
                    msg = '文件格式不允许';
                    break;
                case 'F_DUPLICATE':
                    msg = '文件已存在';
                    break;
                default:
                    msg = code;
            }
            layer.msg(msg, {icon: 2, time: 2000});
        });

        $('.uploader-file-queue').on('click', '.icon-remove', function () {

            var id = $(this).parent().parent().attr('id');
            // 删除队列中的文件
            uploader.removeFile(id, true);
            // 删除dom节点
            $(this).parent().parent().remove();

        });

        // 归档文件：删除文档
        $('.document-unlink-btn').click(function () {
            var _path = $(this).prev().val();
            var _id = $(this).next().val();
            $.ajax({
                url: '/Project/removeDocument',
                type: 'POST',
                data: {
                    id: _id,
                    path: _path
                },
                dataType: 'json',
                success: function (response) {
                    if (response.flag == 1) {
                        $('#MessageText').html('<p><i class="icon-ok-sign text-success"></i>&nbsp;' + response.msg + '</p>');
                        $('#MessageModal').modal('show');
                        setTimeout(function () {
                            location.reload();
                        }, 1000);
                    } else {
                        $('#MessageText').html('<p><i class="icon-remove-sign text-danger"></i>&nbsp;' + response.msg + '</p>');
                        $('#MessageModal').modal('show');
                        setTimeout(function () {
                            $('#MessageModal').modal('hide');
                        }, 1000);
                    }
                }
            });
        });

        // 评论区：跳转楼层
        var floorTotal = $('.message-board').children('.floor').length; //获取到总楼层数
        if (floorTotal > 0) {   //当楼层数量大于指定值时才显示跳转楼层dom
            $('#jumpFloor').removeClass('sr-only');
        }
        $('.jump-info b').text(floorTotal);

        // 讨论区：发表提交
        $('#submit-discuss-content').click(function () {

            var _id = $(this).attr('discuss_id');

            if (editor.getValue()) {    //如果内容为空不允许提交
                var loading = layer.load(2, {
                    shade: [0.5, '#fff'] //0.1透明度的白色背景
                });

                $.ajax({
                    url: '/Project/addDiscussContext',
                    type: 'POST',
                    data: {
                        discuss_id: _id,
                        discuss_context: editor.getValue(),
                        floor: (floorTotal + 1),
                        atta: attachmentData,
                        count: $(this).attr('count')
                    },
                    dataType: 'json',
                    success: function (response) {

                        if (response.flag > 0) {
                            SUB_NAME = response.id;
                            PAGE = response.pg;
                            SUB_ID = response.flag;
                            if (uploader.getFiles().length > 0) {
                                //$('#LAYER_TMP_PROMPT .prompt-msg').text('正在上传文件');
                                uploader.upload();
                            } else {
                                location.href = '/Project/details/tab/discuss/id/' + response.id + '/p/' + response.pg;
                                layer.msg(response.msg, {icon: 1, time: 2000})
                                setTimeout(function () {
                                    location.href = '/Project/details/tab/discuss/id/' + response.id + '/p/' + response.pg;
                                }, 2000);
                            }
                        } else {
                            layer.msg(response.msg, {icon: 2, time: 2000});
                            setTimeout(function () {
                                layer.closeAll();
                            }, 2000);
                        }

                    }
                });
            } else {
                layer.msg('请输入点内容吧');
            }
        });

        $('#logModal').modal({
            backdrop: true,
            show: false
        });

        // 点击激活modal
        $('.modal-btn-focus').click(function () {
            $('#logModal').modal('show');
        });

        // 项目计划：点击编辑激活修改
        $('.plan-table').on('click', '.editor-btn', function () {
            // 获取到当前点击元素的父节点tr/td
            var _td = $(this).parent();
            var _tr = $(this).parent().parent();
            var plan_project = $(this).attr('plan_project');
            var plan_node = $(this).attr('plan_node');
            // 根据当前点击按钮的步骤值的大小判断picker插件显示的位置
            var _step = $(this).attr('step');
            var picker_position = '';
            //当步骤数大于3时显示在上方
            if (_step > 3) {
                picker_position = 'top-left';
            } else {
                picker_position = 'bottom-left';
            }
            _td.html('<div class="btn-group">' +
                '<button type="button" class="btn btn-default btn-sm td-cancel-btn" plan_project="' + plan_project + '" step="' + _step + '" plan_node="' + plan_node + '">' +
                '<i class="icon-remove"></i></button>' +
                '<button type="button" class="btn btn-default btn-sm td-save-btn" plan_project="' + plan_project + '" plan_node="' + plan_node + '">' +
                '<i class="icon-ok"></i></button></div>');
            // 获取到对应的栏位数据
            var start_time_text = _tr.find('.start_time').text();
            var complete_time_text = _tr.find('.complete_time').text();
            var comments_text = _tr.find('.comments').html();
            comments_text = comments_text.replace(/<br>/g, '\r\n');//替换<br>标签为\r\n
            var prev_td = _td.prev().css('height');

            //console.log(comments_text);
            // 将对应的栏位数据填充到input
            _tr.find('.start_time').html('<input type="text" name="start_time" readonly class="form-control input-sm start_time_picker" value="' + start_time_text + '">');
            _tr.find('.complete_time').html('<input type="text" name="complete_time" readonly class="form-control input-sm complete_time_picker" value="' + complete_time_text + '">');
            _tr.find('.comments').html('<textarea style="height: ' + prev_td + ';" type="text" name="comments" class="form-control input-sm comments_textarea">' + comments_text + '</textarea>');
            _tr.find('.steps').html('<select class="steps" name="steps" lay-verify="required"><option value="0">未开始</option><option value="1">进行中</option><option value="2">已完成</option></select>');
            // 初始化时间组件
            $('.start_time_picker,.complete_time_picker').datetimepicker({
                language: 'zh-CN',
                format: 'yyyy-mm-dd',
                weekStart: 1,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                pickerPosition: picker_position,
                startView: 2,
                minView: 2,
                forceParse: 0
            });
        });

        // 项目计划：点击取消回退到正常状态
        $('.plan-table').on('click', '.td-cancel-btn', function () {
            // 获取到当前点击元素的父节点tr/td
            var _td = $(this).parent().parent();
            var _tr = $(this).parent().parent().parent();
            var _getId = $(this).attr('plan_project');
            var _gate = $(this).attr('step');
            var _pid = $(this).attr('plan_node');

            _td.html('<button class="editor-btn btn btn-default btn-sm" plan_project="' + _getId + '" step="' + _gate + '" plan_node="' + _pid + '"><i class="icon-edit"></i></button>');

            // 获取到原始数据
            var start_time_text = _tr.find('.start_time').attr('originally');
            var complete_time_text = _tr.find('.complete_time').attr('originally');
            var comments_text = _tr.find('.comments').attr('originally');
            var steps_text = _tr.find('.step_dis').html()
            //console.log(comments_text);
            // 恢复到原始数据
            _tr.find('.start_time').html(start_time_text);
            _tr.find('.complete_time').html(complete_time_text);
            _tr.find('.comments').html(comments_text);
            _tr.find('.steps').html(steps_text);
        });


        // 项目计划：点击保存提交当前修改数据
        $('.plan-table').on('click', '.td-save-btn', function () {
            var plan_project = $(this).attr('plan_project');
            var plan_node = $(this).attr('plan_node');
            var _parent_tr = $(this).parents('tr');
            var plan_start_time = _parent_tr.find('input[name=plan_start_time]').val();
            var plan_complete_time = _parent_tr.find('input[name=plan_complete_time]').val();
            var start_time = _parent_tr.find('input[name=start_time]').val();
            var complete_time = _parent_tr.find('input[name=complete_time]').val();
            var comments = _parent_tr.find('textarea[name=comments]').val();
            var steps = _parent_tr.find('select[name=steps]').val();

            // 判断用户是否
            if (start_time == '') {
                layer.msg('填写开始时间！', {time: 2000});
                return false;
            }

            if (complete_time != '' && Date.parse(complete_time) < Date.parse(start_time)) {
                layer.msg('计划结束时间不得小于实际开始时间！', {time: 2000});
                return false;
            }

            $.ajax({
                url: ThinkPHP['AJAX'] + '/Project/plan',
                type: 'POST',
                data: {
                    plan_project: plan_project,
                    plan_node: plan_node,
                    start_time: start_time,
                    plan_stop_time: complete_time,
                    comments: comments,
                    steps: steps
                },
                dataType: 'json',
                beforeSend: function () {
                    $('#loading').removeClass('sr-only');
                },
                success: function (response) {
                    if (response.flag > 0) {
                        setTimeout(function () {
                            layer.msg(response.msg, {icon: 1, time: 2000});
                            location.reload();
                        }, 1000);
                    } else {
                        setTimeout(function () {
                            layer.msg(response.msg, {icon: 2, time: 2000});
                            location.reload();
                        }, 1000);
                    }
                }
            });
        });

        // 项目计划：点击完成提交当前完成时间
        $('.plan-table').on('click', '.btn-mark', function () {

            if ($(this).hasClass('success_btn')) {

                layer.msg('此项目已经处于完成状态！', {icon: 5, time: 2000});

            } else {

                var plan_project = $(this).attr('plan_project');
                var plan_node = $(this).attr('plan_node');
                var _parentTr = $(this).parents('tr');

                var startTime = _parentTr.find('.start_time').text();
                var completeTime = _parentTr.find('.complete_time').text();
                var plan_complete_time = _parentTr.find('.plan_complete_time').text();

                // 判断用户是否
                if (startTime == '') {
                    layer.msg('请先设置的时间！', {time: 2000});
                    return false;
                }
                if (completeTime == '') {
                    layer.msg('请先设置的时间！', {time: 2000});
                    return false;
                }
                if (plan_complete_time != '') {
                    layer.msg('此项目已经处于完成状态！', {time: 2000});
                    return false;
                }

                //loading层
                var load = layer.load(2, {
                    shade: [0.5, '#fff'] //0.1透明度的白色背景
                });

                $.ajax({
                    url: ThinkPHP['AJAX'] + '/Project/mark',
                    type: 'POST',
                    data: {
                        plan_project: plan_project,
                        plan_node: plan_node,
                        start_time: startTime,
                        plan_stop_time: completeTime,
                    },
                    dataType: 'json',

                    success: function (response) {
                        if (response.flag > 0) {
                            layer.msg('操作成功!', {icon: 1, time: 2000})
                            setTimeout(function () {
                                location.reload();
                            }, 1000);
                        } else {
                            setTimeout(function () {
                                layer.msg('操作失败!', {icon: 2, time: 2000})
                                $('#MessageModal').modal('hide');
                                layer.close(load)
                            }, 1000);
                        }
                    }
                });
            }

        });

        // 归档文件：切换Gate
        $('#gateList li').click(function () {
            var gate = $(this).attr('gate');
            var gateMilestone = $(this).text();
            var gateNumNode = $('#gateNum');
            var documentProjectGate = $('#documentProjectGate');
            gateNumNode.text(gateMilestone);
        });


        //监听部门改变
        form.on('select(change)', function (data) {
            $.ajax({
                url: ThinkPHP['AJAX'] + '/Project/ajaxChangeDepartment',
                type: 'POST',
                data: {
                    dpmt: data.value
                },
                dataType: 'json',
                success: function (response) {
                    var _html = '';
                    if (response.flag > 0) {
                        for (key in response.data) {
                            _html += '<li email="' + response.data[key].email + '" user-id="' + response.data[key].id + '" title="' + response.data[key].nickname + '">' + response.data[key].nickname + '</li>';
                        }
                        $('#cc-person-list').html(_html);
                    } else {
                        $('#cc-person-list').html('<center><span class="empty-cc"><i class="icon-info-sign"></i>&nbsp;' + response.msg + '</span></center>');
                    }
                }
            });
        });

        // 回复区 点击回复出现输入框
        $('.message-board').on('click', '.reply-btn', function () {

            $('.reply-context').css('display', 'none');

            $(this).parents('.floor').find('.reply-context').css('display', 'block')
            $(this).parents('.floor').find('.reply-context textarea').focus();

        });

        // 回复区 点击取消隐藏输入框
        $('.message-board').on('click', '.close-reply', function () {
            $(this).parents('.reply-context').hide();
        });

        // 回复提交
        $('.message-board').on('click', '.reply-submit', function () {

            var strValue = $(this).parents('.reply-form').find('.reply-textarea').val();
            var string = strValue.replace(/\&nbsp\;/ig, ' ');

            //如果内容为空不允许提交
            if ($.trim(string).length < 1) {
                layer.msg('内容不得为空', {icon: 2, time: 2000});
                return false;
            }

            var data = new Object();

            data.context = ($(this).parents('.reply-form').find('.reply-textarea').val());
            data.tyep = ($(this).parents('.reply-form').find('input[name = type]').val());
            data.id = ($(this).parents('.reply-form').find('input[name = id]').val());
            data.email = ($(this).parents('.reply-form').find('input[name = email]').val());
            data.discuss = ($(this).parents('.reply-form').find('input[name = discussId]').val());
            //data.floor = $(this).attr('floor_id');
            data.floor = $(this).parents('.floor').children('.reply-hin').text();
            data.url = window.location.href;
            data.count = $(this).parents('.floor').children('.reply-hin').text();

            var index = layer.load(2, {
                shade: [0.5, '#fff'] //0.1透明度的白色背景
            });

            $.ajax({
                url: '/Project/reply',
                type: 'POST',
                data: data,
                dataType: 'json',

                success: function (response) {
                    if (response.flag > 0) {
                        layer.msg(response.msg, {icon: 1, time: 2000})
                        setTimeout(function () {
                            location.href = '/Project/details/tab/discuss/id/' + response.id + '/p/' + response.pg;
                        }, 2000);
                    } else {
                        layer.msg(response.msg, {icon: 2, time: 2000})
                        setTimeout(function () {
                            layer.close(index);
                            location.reload();
                        }, 2000)
                    }
                }
            });

            return false;
        });

        // 评论区：跳转楼层
        $('#jump').click(function () {
            var floor = $(this).prev().val();
            if ($.trim(floor) == '') {
                layer.msg('请输入跳转的楼层');
                return false;
            } else {
                var regular = /^[1-9]([0-9]{1,})?$/;
                if (!regular.test(floor)) {
                    layer.msg('请输入正确的楼层');
                    return false;
                } else {
                    if (floor > floorTotal) {
                        layer.msg('超过总楼层数');
                        return false;
                    } else {
                        var top = $('div[name=floor' + floor + ']').offset().top - 90;   //获取到跳转楼层到页面顶部的距离
                        $('#content-box').scroll(top);
                    }
                }
            }
        });

        // 回复评论textarea
        /*$('.reply-context .reply-textarea').mousemove(function(){
         $(this).css("border","1px solid #66afe9");

         });*/
        // 讨论区：打开添加抄送人模态框
        $('#add-cc-people').click(function () {
            $('#CCpeopleModal').modal('show');
        });

        /*$('#CCpeopleModal').on('hidden.bs.modal', function (e) {
         $('#content-box').mCustomScrollbar('update');
         })*/

        // 讨论区：点击抄送人添加到抄送人员列表
        $('#cc-person-list').on('click', 'li', function () {
            $('#has-been-box').removeClass('sr-only');
            var flag = true;
            var email = $(this).attr('email');
            var nickname = $(this).text();
            var user_id = $(this).attr('user-id');
            var _html = '<li email="' + email + '" user-id="' + user_id + '">' + nickname + '<div class="remove-cc"><i class="icon-remove"></i></div></li>';
            var child_length = $('#addList').children('li').length;
            if (child_length > 0) {
                $('#addList li').each(function (index) {
                    if (user_id == $(this).attr('user-id')) {
                        flag = false;
                        return false;
                    }
                });
            }
            if (!flag) {
                layer.msg(nickname + '已存在', {offset: '260px'});
            } else {
                $('#addList').append(_html);
            }
        });

        // 讨论区：点击删除抄送人
        $('#addList').on('click', 'li', function () {
            var user_id = $(this).attr('user-id');
            if ($('#ccPersonList i').children('li').length > 0) {
                $('#ccPersonList i li').each(function () {
                    if (user_id == $(this).attr('user-id')) {
                        $(this).remove();
                    }
                });
            }
            $(this).remove();
            if ($('#addList').children('li').length == 0) {
                if (!$('#has-been-box').hasClass('sr-only')) {
                    $('#has-been-box').addClass('sr-only');
                }
            }
        });

        // 讨论区：确定添加抄送人
        $('#done-cc-list').click(function () {
            var _length = $('#addList').children('li').length;
            if (_length > 0) {  // 如果抄送人不为空，则将所有的抄送人的id拼接为字符串保存
                var idList = '';
                var _html = '';
                $('#addList li').each(function () {
                    _html += '<li email="' + $(this).attr('email') + '" user-id="' + $(this).attr('user-id') + '">' + $(this).text() + '<i class="icon-remove-sign"></i></li>\r\n'
                    idList += $(this).attr('user-id') + ',';
                });
                $('#ccPersonList i').html(_html);
                $('#cc_list').val(idList);
            }
            $('#CCpeopleModal').modal('hide');
        });

        // 讨论区：删除抄送人
        $('#ccPersonList i').on('click', 'li i', function () {
            var _parent = $(this).parent();
            var user_id = _parent.attr('user-id');
            if ($('#addList').children('li').length > 0) {
                $('#addList li').each(function () {
                    if (user_id == $(this).attr('user-id')) {
                        $(this).remove();
                    }
                });
            }
            $(this).remove();
            if ($('#addList').children('li').length == 0) {
                if (!$('#has-been-box').hasClass('sr-only')) {
                    $('#has-been-box').addClass('sr-only');
                }
            }
            _parent.remove();
        })

        // 讨论区：重置
        $('#reset-cc-people').click(function () {
            $(this).parent().find('.not-default').html('');
            $('#addList').html('');
            if ($('#addList').children('li').length == 0) {
                if (!$('#has-been-box').hasClass('sr-only')) {
                    $('#has-been-box').addClass('sr-only');
                }
            }
        });


    });

});

// 当页面加载完成后，检查地址栏是否存在楼层，如果存在则直接锁定到该楼层
window.onload = function () {
    var floorSize = $('.message-board').children('.media').length; //获取到总楼层数
    if ($('#floorNum')) {
        var floorNum = $('#floorNum').val();
        if ($.trim(floorNum) != '') {
            var regular = /^[1-9]([0-9]{1,})?$/;
            if (regular.test(floorNum)) {
                if (floorNum <= floorSize) {
                    var top = $('div[name=floor' + floorNum + ']').offset().top - 90;   //获取到跳转楼层到页面顶部的距离
                    $('#content-box').scroll(top)
                }
            }
        }
    }
};

